<template>
  <el-dialog :title="this.formData.id?'编辑权限':'新增权限'" :visible="showDialog" @close="closeDialog">
    <!-- 表单 -->
    <el-form ref="perForm" :model="formData" :rules="rules" label-width="120px">
      <el-form-item label="权限名称" prop="name">
        <el-input v-model="formData.name" style="width: 90%" />
      </el-form-item>
      <el-form-item label="权限标识" prop="code">
        <el-input v-model="formData.code" style="width: 90%" />
      </el-form-item>
      <el-form-item label="权限描述">
        <el-input v-model="formData.description" style="width: 90%" />
      </el-form-item>
      <el-form-item label="开启">
        <el-switch
          v-model="formData.enVisible"
          active-value="1"
          inactive-value="0"
        />
      </el-form-item>
    </el-form>
    <el-row slot="footer" type="flex" justify="center">
      <el-col :span="6">
        <el-button size="small" type="primary" @click="handlerConfirm">确定</el-button>
        <el-button size="small" @click="closeDialog">取消</el-button>
      </el-col>
    </el-row>
  </el-dialog>
</template>

<script>
export default {
  props: {
    showDialog: {
      type: Boolean,
      default: false,
    },
    validate:{//校验数据==用于校验是否重复
        type:Array,
        default:()=>[]
    }
  },
  data() {
     // 权限标识校验
    const validateCode = (rule, value, callback) => {
      let existence
      if (this.formData.id) {
        // 编辑，排查当前部门，允许自己修改自己
        existence = this.validate.filter(t => t.id !== this.formData.id).find(t => t.code === value)
      } else {
        // 新增
        existence = this.validate.find(t => t.code === value)
      }
      existence ? callback(new Error('权限标识重复')) : callback()
    }
    // 权限名称校验
    const validatename = (rule, value, callback) => {
      let existence
      if (this.formData.id) {
        // 编辑，排查当前部门，允许自己修改自己
        existence = this.validate.filter(t => t.id !== this.formData.id).find(t => t.name === value)
      } else {
        // 新增
        existence = this.validate.find(t => t.name === value)
      }
      existence ? callback(new Error('权限名称重复')) : callback()
    }
    return {
      formData: {
        name: "", // 名称
        code: "", // 标识
        description: "", // 描述
        enVisible: "0", // 开启
      },
      rules: {
        name: [
          { required: true, message: "权限名称不能为空", trigger: "blur" },
          { validator: validatename, trigger: 'blur' },

        ],
        code: [
          { required: true, message: "权限标识不能为空", trigger: "blur" },
          { validator: validateCode, trigger: 'blur' },
        ],
      },
    };
  },
  methods: {
    //关闭Dialog、重置表单
    closeDialog() {
        
      this.$emit("update:showDialog", false);
      this.formData=this.$options.data().formData
    },
    //确认
    handlerConfirm(){
      this.$refs.perForm.validate(valid=>{
            if(valid){
                this.$emit('confirm',this.formData)
            }
        })
        
    }
  },
};
</script>

<style>
</style>